<script setup>
import { computed, reactive, ref, toRaw, watch, nextTick } from "vue";
import {
  CloseOutlined,
  SearchOutlined,
  LeftOutlined,
  PlusOutlined,
} from "@ant-design/icons-vue";

import { useVModel } from "@vueuse/core";
import request from "@/common/utils/request";
import _ from "lodash";

const props = defineProps({
  formDataA: {
    type: Array,
    default: () => [],
  },
  formRefA: {
    type: Object,
    default: () => {},
  },
  validateInfosA: {
    type: Object,
    default: () => {},
  },
  rulesRefA: {
    type: Object,
    default: () => {},
  },
  useFormA: {
    type: Function,
    default: () => {},
  },
  isValidate: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits([
  "update:formDataA",
  "update:formRefA",
  "update:validateInfosA",
  "update:useFormA",
  "update:rulesRefA",
]);
const formData = useVModel(props, "formDataA", emit);
const validateInfos = useVModel(props, "validateInfosA", emit);
const formRef = useVModel(props, "formRefA", emit);
const useForm = useVModel(props, "useFormA", emit);
const rulesRef = useVModel(props, "rulesRefA", emit);
let validateKeywords = async (rule, value, item) => {
  if (
    item.isRequired &&
    (!formRef.value[rule.field] || formRef.value[rule.field].length == 0)
  ) {
    return Promise.reject("请添加" + item.label);
  } else {
    return Promise.resolve();
  }
};
setTimeout(() => {
  formData.value.forEach((item, index) => {
    if (item.formType == "multiSelect") {
      formRef.value["value" + index] = formRef.value["value" + index]
        ? formRef.value["value" + index]
        : [];
    } else {
      formRef.value["value" + index] = formRef.value["value" + index]
        ? formRef.value["value" + index]
        : null;
    }
    // 有默认值
    if (item.defaultValue) {
      if (item.formType == "keywords") {
        formRef.value["value" + index] = formRef.value["value" + index]
          ? formRef.value["value" + index]
          : item.defaultValue;
      } else {
        item.placeholder = "示例:" + item.defaultValue;
      }
    }
    if (item.formType == "select") {
      rulesRef.value["value" + index] = [
        {
          required: props.isValidate ? item.isRequired : false,
          message: "请选择" + item.label,
          trigger: "blur",
        },
      ];
    }
    if (item.formType == "keywords" || item.formType == "multiSelect") {
      rulesRef.value["value" + index] = [
        {
          required: props.isValidate ? item.isRequired : false,
          trigger: "blur",
          validator: (rule, value) => validateKeywords(rule, value, item),
        },
      ];
    } else {
      rulesRef.value["value" + index] = [
        {
          required: props.isValidate ? item.isRequired : false,
          message: "请输入" + item.label,
          trigger: "blur",
        },
      ];
    }
  });
  validateInfos.value = useForm.value(
    formRef.value,
    rulesRef.value
  ).validateInfos;
}, 1000);

const newKeywordsInputRef = ref(null);
const showAddKeywords = (item) => {
  item.newKeywordsAdding = true;
  nextTick(() => {
    newKeywordsInputRef.value[0].focus();
  });
};
const addKeywords = (e, item, index) => {
  if (item.newKeywords) {
    if (!formRef.value["value" + index]) {
      formRef.value["value" + index] = [];
    }
    formRef.value["value" + index].push(item.newKeywords);
    item.newKeywords = "";
    item.newKeywordsAdding = false;
  } else {
    item.newKeywordsAdding = false;
  }
};
const removeKeywords = (index, tagIndex) => {
  formRef.value["value" + index].splice(tagIndex, 1);
};
</script>

<template>
  <div class="form-wrapper">
    <a-form-item
      v-for="(item, index) of formData"
      :key="index"
      v-bind="validateInfos['value' + index]"
    >
      <template #label>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
          "
        >
          <div>{{ item.label }}</div>
          <!-- <div v-if="item.patternIds && item.patternIds.length > 0">
                    <a-button type="link" style="padding: 0; margin: 0"
                        @click="showMaterialListPop(item, index)">智能推荐</a-button>
                </div> -->
        </div>
      </template>
      <template v-if="item.formType == 'input'">
        <a-input
          v-model:value="formRef['value' + index]"
          :placeholder="item.placeholder || '请输入'"
        />
      </template>
      <template v-if="item.formType == 'textarea'">
        <a-textarea
          v-model:value="formRef['value' + index]"
          :placeholder="item.placeholder || '请输入'"
          :rows="4"
        />
      </template>
      <template
        v-if="
          item.formType == 'select' && item.options && item.options.length > 0
        "
      >
        <a-select
          :getPopupContainer="(node) => node.parentNode"
          v-model:value="formRef['value' + index]"
          :placeholder="item.placeholder || '请选择'"
          :options="
            item.options.map((item) => ({
              label: item,
              value: item,
            }))
          "
        >
        </a-select>
      </template>
      <template v-if="item.formType == 'keywords'">
        <div class="keywords-wrap">
          <a-tag
            closable
            style="
              border-radius: 6px;
              white-space: pre-wrap;
              word-break: break-all;
              margin-bottom: 8px;
            "
            v-for="(tagItem, tagIndex) of formRef['value' + index]"
            :key="tagIndex"
            @close.prevent="removeKeywords(index, tagIndex)"
            >{{ tagItem }}</a-tag
          >
          <a-input
            v-model:value="item.newKeywords"
            style="width: 80px; height: 24px"
            v-if="item.newKeywordsAdding"
            @pressEnter="(e) => addKeywords(e, item, index)"
            @blur="addKeywords(null, item, index)"
            ref="newKeywordsInputRef"
          />
          <div v-else class="add-keyword-button" @click="showAddKeywords(item)">
            <PlusOutlined />
            <span style="margin-left: 5px">添加</span>
          </div>
        </div>
      </template>
      <template
        v-if="
          item.formType == 'multiSelect' &&
          item.options &&
          item.options.length > 0
        "
      >
        <a-select
          :getPopupContainer="(node) => node.parentNode"
          v-model:value="formRef['value' + index]"
          :placeholder="item.placeholder || '请选择'"
          mode="multiple"
          :options="
            item.options.map((item) => ({
              label: item,
              value: item,
            }))
          "
        >
        </a-select>
      </template>
    </a-form-item>
  </div>
</template>

<style lang="less" scoped>
.keywords-wrap {
  min-height: 60px;
  border: 1px solid #d9d9d9;
  display: flex;
  flex-wrap: wrap;
  padding: 10px;

  .add-keyword-button {
    width: 60px;
    height: 24px;
    background-color: #fafafa;
    border: 1px dashed #ccc;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 6px;
    font-size: 12px;
  }
}
</style>
